require('normalize.css/normalize.css');
require('styles/App.css');

import React from 'react';

//获取图片相关的源信息
let imagesData = require('../data/imgdata.json');

//利用自执行,将图片名信息转换成图片URL路径信息
imagesData = ((imgDataArr)=> {
	for (var i = 0,length=imgDataArr.length; i < length; i++) {
		var oneImgData = imgDataArr[i];
		oneImgData.imgUrl = require('../images/' + oneImgData.fileName);
		imgDataArr[i] = oneImgData;
	}
	return imgDataArr;
})(imagesData);

/**
 * [getRangeRandom 生成随机数]]
 * @param  {[type]} low  [最小值]
 * @param  {[type]} high [最大值]
 * @return {[type]}      [description]
 */
function getRangeRandom(low,high){
	return ~~(Math.random()*(high - low + 1) + low);
}

/**
 * 图片组件
 */
class ImgFigure extends React.Component{
	/**
	 * [handleClick 点击事件]
	 * @param  {[type]} e [description]
	 * @return {[type]}   [description]
	 */
	handleClick(e){

		if(this.props.arrange.isCenter){
			this.props.inverse();
		}else {
			this.props.center();
		}

		e.stopPropagation();
		e.preventDefault();
	}

	render(){

		let styleObj = {};
		let figureClassName = 'img-figure';
		figureClassName += this.props.arrange.isInverse ? '  is-inverse' : '';
		//如果props属性上指定了这张图片的位置,则使用
		if(this.props.arrange.pos){
			styleObj = this.props.arrange.pos;
		}
		//如果图片有选转角度,且不为0
		if(this.props.arrange.rotate){
			['msTransform','MozTransform','WebkitTransform','transform'].forEach(function(val){
				styleObj[val] = 'rotate(' + this.props.arrange.rotate + 'deg)';
			}.bind(this));
		}
		if(this.props.arrange.isCenter){
			styleObj.zIndex = 99;
		}else{
			styleObj.zIndex = 'inherit';
		}
		return(
			<figure className={figureClassName} style={styleObj} ref='figure' onClick={this.handleClick.bind(this)}>
				<img src={this.props.data.imgUrl} alt={this.props.data.title} />
				<figurecaption>
					<h2 className='img-title'>{this.props.data.title}</h2>
					<div className='img-back' onClick={this.handleClick.bind(this)}>
							<p>{this.props.data.desc}</p>
					</div>
				</figurecaption>
			</figure>
		)
	}


}

/**
 * 控制器组件
 */
class Control extends React.Component{

	handleClick(e){
		if(this.props.arrange.isCenter){
			this.props.inverse();
		}else{
			this.props.center();
		}
		e.stopPropagation();
		e.preventDefault();

	}

	render(){
		let controlClassName = 'control-unit';

		if(this.props.arrange.isCenter){
			controlClassName += '  is-center';
		}
		if(this.props.arrange.isInverse){
			controlClassName += '  is-inverse';
		}

		return(
			<span className={controlClassName} onClick={this.handleClick.bind(this)}></span>
		)
	}
}
/**
 * 对外接口
 */
class AppComponent extends React.Component {
	constructor(props){
		super(props)

		this.state = {
			imgArrangeArr:[
				// {
				// 	pos:{
				// 		left:0,
				// 		top:0
				// 	},
				// 	rotate:0,
				// 	isInverse:false  //图片正反面
				// },
				// isCenter:false  //图片是否居中
			]
		};
		/**
		 * [CONSTANT 图片定位的取值范围]
		 * @type {Object}
		 */
		this.CONSTANT={
			centerPos:{
				left:0,
				top:0
			},
			hPosRange:{				//两侧的取值范围
				leftSecX:[0,0],
				rightSecX:[0,0],
				y:[0,0]
			},
			vPosRange:{				//顶部的取值范围
				topY:[0,0],
				x:[0,0]
			}
		};

	}
	/**
	 * [rearrange 重新排版图片]
	 * @param  {[type]} centerIndex [中心图标下标]
	 * @return {[type]}             [description]
	 */
	rearrange(centerIndex){
		let imgArrangeArr = this.state.imgArrangeArr,
				CONSTANT = this.CONSTANT,
				centerPos = CONSTANT.centerPos,
				hPosRange = CONSTANT.hPosRange,
				vPosRange = CONSTANT.vPosRange,
				leftSecX = hPosRange.leftSecX,
				rightSecX = hPosRange.rightSecX,
				hY = hPosRange.y,
				topY = vPosRange.topY,
				vX = vPosRange.x,				
				topImgArr = [],//顶部图片数组
				topImgNum = ~~(Math.random()*2),//顶部图片的数量
				topImgIndex = 0,//顶部图片下标
				imgCenterArr = imgArrangeArr.splice(centerIndex, 1);//中心图片

			//居中图片
			imgCenterArr[0]={
				pos:centerPos,
				rotate:0,
				isCenter:true
			};

			//顶部图片
			topImgIndex = ~~(Math.random()*(imgArrangeArr.length - topImgNum));
			topImgArr = imgArrangeArr.splice(topImgIndex, topImgNum);
			topImgArr.forEach((val,index)=>{
				topImgArr[index] = {
					pos:{
						left:getRangeRandom(vX[0] , vX[1]),
						top:getRangeRandom(topY[0] , topY[1])
					},
					rotate:getRangeRandom(-30,30),
					isCenter:false
				}
			});

			//两侧图片
			imgArrangeArr.forEach((val,index)=>{
				let LORX = null,
						k = imgArrangeArr.length/2;

				LORX = index < k ? leftSecX : rightSecX;
				
				imgArrangeArr[index] = {
					pos:{
						left : getRangeRandom(LORX[0] , LORX[1]),
						top: getRangeRandom(hY[0] , hY[1])
					},
					rotate:getRangeRandom(-30,30),
					isCenter:false
				}

			});
	

			//把取出来的数据返回
			if(topImgArr && topImgArr[0]){
				imgArrangeArr.splice(topImgIndex, 0, topImgArr[0]);
			}
			imgArrangeArr.splice(centerIndex, 0, imgCenterArr[0]);

			//设置init状态
			this.setState({
				imgArrangeArr:imgArrangeArr
			});

	}
	/**
	 * [componentDidMount 组件加载后,为每张图片计算其位置的范围]
	 * @return {[type]} [description]
	 */
	componentDidMount(){

		//首先拿到舞台的大小
		let stageDOM = this.refs.stage,
				stageW = stageDOM.scrollWidth,
				stageH = stageDOM.scrollHeight,
				halfStageW = ~~(stageW/2),
				halfStageH = ~~(stageH/2);

		//拿到图片的大小
		let imgDOM = this.refs.imgFigure0.refs.figure,
				imgW = imgDOM.scrollWidth,
				imgH = imgDOM.scrollHeight,
				halfImgW = ~~(imgW/2),
				halfImgH = ~~(imgH/2);

		//计算中心点图片位置
		this.CONSTANT.centerPos = {
			left:halfStageW - halfImgW,
			top:halfStageH-halfImgH 
		}	
		//计算左右两侧图片的位置
		this.CONSTANT.hPosRange = {
			leftSecX:[-halfImgW , halfStageW - halfImgW * 3],
			rightSecX:[halfStageW + halfImgW , stageW - halfImgW],
			y:[-halfImgH , stageH - halfImgH]
		}
		//计算中心顶端的图片的位置
		this.CONSTANT.vPosRange = {
			topY:[-halfImgH , halfStageH - halfImgH * 3],
			x:[halfStageW - halfImgH , halfStageH]
		}

		//调用重新排布
		this.rearrange(0);
	}
	/**
	 * [inverse 图片反转]
	 * @param  {[type]} index [要反转图片的下标]
	 * @return {[type]}       [description]
	 */
	inverse(index){
		return ()=>{
			let imgArrangeArr = this.state.imgArrangeArr;
			imgArrangeArr[index].isInverse = !imgArrangeArr[index].isInverse;

			//设置init状态
			this.setState({
				imgArrangeArr:imgArrangeArr
			});
		}
	}
	/**
	 * [center 居中图片]
	 * @param  {[type]} index [要居中图片的下标]
	 * @return {[type]}       [description]
	 */
	center(index){
		return ()=>{
			this.rearrange(index);
		}
	}

  render() {

  	var controlUnits = [],
  			imgFigures = [];

  	//加载ImgFigure组件
  	imagesData.forEach((value,index)=>{
  		// console.log(this);
  		// debugger;
  		if(!this.state.imgArrangeArr[index]){
  			this.state.imgArrangeArr[index] = {
  				pos:{
  					left : 0,
  					top: 0
  				},
  				rotate:0,
  				isInverse:false,
  				isCenter:false
  			}
  		}
  		//图片组件
  		imgFigures.push(
  			<ImgFigure 
  				key={index}
  				data={value} 
  				ref={'imgFigure'+index}
  				arrange={this.state.imgArrangeArr[index]}
  				inverse={this.inverse(index).bind(this)}
  				center={this.center(index).bind(this)}
  			/>
  		);
  		//控制组件
  		controlUnits.push(
  			<Control 
  				key={index}
  				arrange={this.state.imgArrangeArr[index]}
  				inverse={this.inverse(index).bind(this)}
  				center={this.center(index).bind(this)}
  			/>
  		);

  	});

    return (
      <section className="stage" ref='stage'>
      	<article className="img-sec">
      		{imgFigures}
      	</article>
      	<nav className="control">
      		{controlUnits}
      	</nav>
      </section>
    );
  }
}

AppComponent.defaultProps = {
};

export default AppComponent;
